package com.common;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.upload.FormFile;

public class PicUpload 
{
	public String picUpload(String path,FormFile file)
	{
	    List<String> list = new ArrayList<String>();
	    list.add("jpg");
	    list.add("jpeg");
	    list.add("gif");
	    list.add("bmp");

	    String fname = file.getFileName();
	    int fsize = file.getFileSize();
	    String ext = fname.substring(fname.lastIndexOf(".") + 1, fname.length());
	   
	    ext = ext.toLowerCase();
	    if (!list.contains(ext)){
	    	System.out.println("file ext error");
	    }
	    if (fsize > 1024 * 1024){
	    	System.out.println("you upload file size overflow");
	    }
	    
	    String fileName = System.currentTimeMillis()+"."+ext;
		FileOutputStream fileOutput;
		try
		{
			 fileOutput = new FileOutputStream(Constant.SYSTEMPATH+path+Constant.PATH_SYMBOL+fileName);
	         fileOutput.write(file.getFileData());
	         fileOutput.flush();
	         fileOutput.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return fileName;
	}
	
	public String createFolder(String path)
	{
		String datefile=String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
		datefile+=Calendar.getInstance().get(Calendar.MONTH)+1;
		datefile+=Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		
		
		File folder=new File(Constant.SYSTEMPATH+path+datefile);
		//if file not exists   create
		if(!folder.exists())
		{
			try
			{
				folder.mkdir();
			}
			catch(Exception e)
			{
				System.out.println("create folder fail");
				e.printStackTrace();
			}
		}
		return datefile;
	}
}
